package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.util.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Reference
    private OrderService orderService;
    @Autowired
    private JedisPool jedisPool;
    //在线体检预约
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        //获取用户的手机号
        String telephone = (String) map.get("telephone");
        //以用户手机号加提示码为参数从redis中获取验证码 对比用户输入的验证码是否正确
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        //校验手机验证码
//        ????
        if(codeInRedis==null||!codeInRedis.equals(validateCode)){
            //输入验证码为空 或者 验证码错误 返回失败提示
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //调用体检预约服务 (预约类型 微信预约)
        map.put("orderType", Order.ORDERTYPE_WEIXIN);
        Result result=null;
        try {
           result = orderService.order(map);
        }catch (Exception e){
            return new Result(false,"预约失败");
        }
        //正确完成预约业务处理
        //预约成功 给用户发送信息
        if (result.isFlag()){
            String orderDate = (String) map.get("orderDate");
            try {
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,orderDate);
            }catch (Exception e){
                System.out.println("发送预约信息失败!");
            }
        }
        //预约成功提示信息
        return result;
    }
    /*
    根据预约id查询预约相关信息
     */
    @RequestMapping("/findById")
    public Result findByid(Integer id){
        try {
            Map map=orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }

    }
}
